using System;
using UnityEngine;

namespace ClassicBehaviorTree
{
    public class TriggerRepeater : Container
    {
        private int _repeatTimes;
        public int RepeatTimes { get => _repeatTimes; set => _repeatTimes = Mathf.Max(0, value); }
        public TriggerRepeater() { }
        public TriggerRepeater(int repeatTimes) { RepeatTimes = repeatTimes; }
        public TriggerRepeater(string repeatTimes) { RepeatTimes = int.Parse(repeatTimes); }
        public override NodeState Update()
        {
            if (RepeatTimes == 0 && _subNodes[0].Update() == NodeState.Success)//repeat forever
            {
                switch (_subNodes[1].Update())
                {
                    case NodeState.Ready:
                        _state = NodeState.Ready;
                        break;
                    case NodeState.Success:
                        Reset();
                        break;
                    case NodeState.Failure:
                        _state = NodeState.Failure;
                        break;
                    case NodeState.Abort:
                        _state = NodeState.Abort;
                        break;
                    default:
                        throw new Exception("This should never happen, but clearly it has.");
                }
            }
            else if (_successCounter < RepeatTimes && _subNodes[0].Update() == NodeState.Success)
            {
                switch (_subNodes[1].Update())
                {
                    case NodeState.Ready:
                        _state = NodeState.Ready;
                        break;
                    case NodeState.Success:
                        _successCounter++;
                        if (_successCounter < RepeatTimes)
                        {
                            Reset();
                        }
                        else
                        {
                            _state = NodeState.Success;
                        }
                        break;
                    case NodeState.Failure:
                        _state = NodeState.Failure;
                        break;
                    case NodeState.Abort:
                        _state = NodeState.Abort;
                        break;
                    default:
                        throw new Exception("This should never happen, but clearly it has.");
                }
            }
            return _state;
        }
    }
}
